package com.Maykk.bytesStream;

import java.io.*;

/**
 * @ClassName: com.Maykk.bytesStream.Demo08
 * @Description: TODO 缓冲区流和字节流速度对比
 * @Author: MaykkStar@163.com
 */
public class Demo08 {
    public static void main(String[] args) throws IOException {
        final String SRC = "./test.mp4";
        final String TO = "./testNew.mp4";
        long startTime = System.currentTimeMillis();
//        method01(SRC, TO); // 共耗时：668620ms
//        method02(SRC, TO); // 共耗时：894ms
//        method03(SRC, TO); // 共耗时：2002ms
        method04(SRC, TO); // 共耗时：304ms
        long endTime = System.currentTimeMillis();
        System.out.println("共耗时：" + (endTime - startTime) + "ms");
    }

    /**
     * 缓冲区字节流一次读取 1k
     *
     * @param src 源文件
     * @param to 新文件
     */
    private static void method04(String src, String to) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(to));

        byte[] bytes = new byte[1024];
        int len;
        while ((len = bis.read(bytes)) != -1) {
            bos.write(bytes, 0, len);
        }

        bis.close();
        bos.close();
    }

    /**
     * 缓冲区字节流一次读取一个字节
     *
     * @param src 源文件
     * @param to  新文件
     */
    private static void method03(String src, String to) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(to));

        int by;
        while ((by = bis.read()) != -1) {
            bos.write(by);
        }

        bis.close();
        bos.close();
    }

    /**
     * 字节流一次读取 1k
     *
     * @param src 源文件
     * @param to  新文件
     */
    private static void method02(String src, String to) throws IOException {
        FileInputStream fis = new FileInputStream(src);
        FileOutputStream fos = new FileOutputStream(to);
        byte[] bytes = new byte[1024];
        int len;
        while ((len = fis.read(bytes)) != -1) {
            fos.write(bytes, 0, len);
        }
        fis.close();
        fos.close();
    }

    /**
     * 字节流一次读取一个字节
     *
     * @param src 源文件
     * @param to  新文件
     */
    private static void method01(String src, String to) throws IOException {
        FileInputStream fis = new FileInputStream(src);
        FileOutputStream fos = new FileOutputStream(to);
        int by;
        while ((by = fis.read()) != -1) {
            fos.write(by);
        }
        fis.close();
        fos.close();
    }
}
